<template>
  <div class="page-common-layout custom-tablePage-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-input
            style="width: 380px;"
            v-model="condition.name"
            placeholder="请输入名称"
          ></a-input>
          <a-range-picker
            :placeholder="['方案报审开始时间', '方案报审结束时间']"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-model="condition.date"
            :show-time="false"
          />
          <a-range-picker
            :placeholder="['提交开始日期', '提交结束日期']"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-model="condition.createTime"
            :show-time="false"
          />
          <a-input
            style="width: 240px;"
            v-model="condition.creator"
            placeholder="请输入提交人"
          ></a-input>
          <a-input
            style="width: 380px;"
            v-model="condition.remark"
            placeholder="请输入描述"
          ></a-input>
          <a-select
            placeholder="请选择专业"
            v-model="condition.major"
            class="project-select"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in majorSource"
              :key="item.dicItemCode"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="table-body-container">
      <div class="table-operate">
        <a-button
          @click="handleWrapPage({}, 1)"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-action="'table_add_11'"
        >
          新增
        </a-button>
      </div>
      <div class="table-main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column
            type="seq"
            width="80"
            title="序号"
            fixed="left"
          ></vxe-column>
          <vxe-column
            field="name"
            title="名称"
            min-width="100"
            fixed="left"
            align="left"
          >
          </vxe-column>
          <vxe-column field="majorDesc" title="专业" fixed="left"> </vxe-column>
          <vxe-column field="time" title="施工图报审时间" fixed="left">
          </vxe-column>
          <vxe-column
            :field="item.key"
            :title="item.title"
            v-for="(item, index) in columns"
            :key="index"
          >
            <template #default="{ row,rowIndex }">
              <div class="files-icon">
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    :class="[
                      row[item.key] &&
                        row[item.key]['fileIdInfo'].length == 0 &&
                        'disabled',
                    ]"
                    @click="handelFileModal(row[item.key], item, row)"
                  />
                </a-tooltip>
                <a-tooltip placement="top" v-action="'down_load_11'">
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    v-if="row[item.key] && row[item.key]['downloadStatus']"
                    type="sync"
                    spin
                  />
                  <a-icon
                    v-else
                    type="download"
                    class="download-btn"
                    :class="[
                      row[item.key] &&
                        row[item.key]['fileIdInfo'].length == 0 &&
                        'disabled',
                    ]"
                    @click="
                      downloadFile(row[item.key], item, row, rowIndex, item.key)
                    "
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="creator" title="提交人" fixed="right">
          </vxe-column>
          <vxe-column field="createTimeStr" title="提交时间" fixed="right">
          </vxe-column>
          <vxe-column field="remark" title="描述" fixed="right"> </vxe-column>
          <vxe-column field="operate" width="160" title="操作" fixed="right">
            <template #default="{ row }">
              <div class="text-button-group">
                <!-- 通知 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    通知
                  </template>
                  <icon-fonts
                    icon="icon-remind"
                    class="contrast"
                    @change="handleNotice(row)"
                  ></icon-fonts>
                </a-tooltip>
                <!-- 查看 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    查看
                  </template>
                  <a-icon type="file-search" @click="handleDetailPage(row)" />
                </a-tooltip>
                <!-- 编辑 -->
                <a-tooltip placement="top" v-action="'table_edit_11'">
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon
                    type="edit"
                    class="edit-btn"
                    @click="handleWrapPage(row, 2)"
                  />
                </a-tooltip>
                <!-- 删除 -->
                <a-tooltip v-action="'file_delete_11'">
                  <template slot="title">
                    删除
                  </template>
                  <a-icon type="delete" @click="handleDelClick(row)" />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="table-pager">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 新增/编辑/查看 -->
    <wrapPage
      :key="wrapPage.key"
      :visible.sync="wrapPage.visible"
      :parameter="wrapPage.row"
      :pageOperate="wrapPage.operate"
      @close="closePage()"
    ></wrapPage>
    <!-- 查看附件 -->
    <viewFileModal
      :visible.sync="viewFileModal.visible"
      :fileList="viewFileModal.fileList"
      :subtitle="viewFileModal.name"
    ></viewFileModal>
    <!-- 通知弹窗 -->
    <noticeModal
      :visible.sync="noticeModal.visible"
      :parameter="noticeModal.row"
    ></noticeModal>
    <!-- 单文件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
    <!--  目录+文件预览 -->
    <treeViewFileModal
      :visible.sync="treeViewFileModal.visible"
      :subtitle="treeViewFileModal.name"
      :dataSource="treeViewFileModal.source"
    ></treeViewFileModal>

    <!-- 详情 -->
    <detailPage
      :key="detailPage.key"
      :visible.sync="detailPage.visible"
      :parameter="detailPage.row"
      @close="closePage()"
    ></detailPage>
  </div>
</template>

<script>
//施工图审
import { mapGetters } from "vuex";
import wrapPage from "./wrapPage.vue";
import detailPage from "./detailPage.vue";
import noticeModal from "./noticeModal.vue";
import { _getUUID } from "@/utils/util.js";
import { downLoadBatchFileByArraybuffer, getToken } from "@/utils/TopVUI";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import { getDicItemByCode } from "@/api/common.js";
import {
  getDrawingReviewHeader,
  pageDrawingReviewBody,
  exportConstructionDrawingReview,
  exportZipByFileIds,
  deleteConstructionDrawingReview,
} from "@/api/design";
//单文件预览
import previewModal from "@/pages/document/minio/previewModal";
//目录+文件预览
import treeViewFileModal from "./treeViewFileModal.vue";
//多文件预览
import viewFileModal from "@/components/extendCustom/view-file-modal";
export default {
  components: {
    wrapPage,
    viewFileModal,
    ScreenConditions,
    noticeModal,
    previewModal,
    treeViewFileModal,
    detailPage,
  },
  data() {
    return {
      //查询条件
      condition: {
        //提交时间
        createTime: [],
        // 提交人：
        creator: "",
        // 备注：
        remark: "",
        // 名称：
        name: "",
        // 专业：
        major: undefined,
        // 报审时间：
        date: [],
      },
      //专业
      majorSource: [],
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      columns: [],
      // 新增/编辑/查看
      wrapPage: {
        visible: false,
        key: _getUUID(),
        row: {},
        operate: 1,
      },
      //查看附件
      viewFileModal: {
        name: "",
        visible: false,
        fileList: [],
      },
      //通知
      noticeModal: {
        visible: false,
        row: {},
      },
      //单文件预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //目录+文件预览
      treeViewFileModal: {
        visible: false,
        name: "",
        source: {},
      },
      //详情
      detailPage: {
        visible: false,
        key: _getUUID(),
        row: {},
      },
    };
  },
  computed: {
    ...mapGetters(["configData", "userInfo"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    async getData() {
      await this.getColumnsHeader();
      await this.getTableData();
      //专业
      this.majorSource = await this.getDicCodeData("major");
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //通知
    handleNotice(row) {
      this.noticeModal.row = row;
      this.noticeModal.visible = true;
    },
    //查看
    handleDetailPage(row) {
      this.detailPage.row = row;
      this.detailPage.key = _getUUID();
      this.detailPage.visible = true;
    },

    // 新增/编辑
    handleWrapPage(row, operate) {
      this.wrapPage.operate = operate;
      this.wrapPage.row = row;
      this.wrapPage.key = _getUUID();
      this.wrapPage.visible = true;
    },

    //预览
    handelFileModal(row, item, record) {
      let { fileIdInfo = [], classifyId } = row;
      if (fileIdInfo.length == 0) {
        return;
      } else if (fileIdInfo.length == 1) {
        let fileItem = fileIdInfo?.[0] ?? {};
        this.viewFile(fileItem);
      } else {
        if (classifyId) {
          this.treeViewFileModal.name = item.title;
          this.treeViewFileModal.source = { classifyId, uuid: record.uuid };
          this.treeViewFileModal.visible = true;
        } else {
          this.viewFileModal.name = item.title;
          this.viewFileModal.fileList = fileIdInfo ?? [];
          this.viewFileModal.visible = true;
        }
      }
    },

    //下载
    downloadFile(file, item, row, rowIndex, key) {
      let { classifyId, fileIdInfo = [] } = file;
      let { uuid } = row;
      let { title } = item;
      if (fileIdInfo.length == 0) {
        return;
      }
      this.tableData[rowIndex][key].downloadStatus = true;
      if (classifyId) {
        exportConstructionDrawingReview({ classifyId, uuid })
          .then((data) => {
            downLoadBatchFileByArraybuffer(data, title);
          })
          .catch((_) => {})
          .finally((_) => {
            this.tableData[rowIndex][key].downloadStatus = false;
          });
      } else {
        let ids = fileIdInfo.map((v) => v.dfsFileUuid);
        exportZipByFileIds({ fileIds: ids.toString() })
          .then((data) => {
            downLoadBatchFileByArraybuffer(data, title);
          })
          .catch((_) => {})
          .finally((_) => {
            this.tableData[rowIndex][key].downloadStatus = false;
          });
      }
    },

    //预览
    viewFile(file) {
      let { previewWay, fileName, url, uuid, unit, bimCadFile } = file;
      let domain = location.origin;
      switch (previewWay) {
        //cad预览
        case "cad":
          window.open(
            `${domain}/#/blackHole/previewCad?uuid=${uuid}&fileName=${fileName}&unit=${unit}`
          );
          return;
        // 模型预览
        case "model":
          let { bhDataSetId } = bimCadFile || {};
          bhDataSetId &&
            window.open(
              `${domain}/#/blackHole/viewDataSetSingleSimple?dataSetId=${bhDataSetId}&name=${fileName}`
            );
          return;
        // 普通文件预览
        default:
          this.previewModal.loading = true;
          this.$refs.previewModal.type = "file";
          this.$refs.previewModal.fileUrl =
            this.kkFileView +
            "/onlinePreview?url=" +
            encodeURIComponent(Base64.encode(url)) +
            "&watermarkTxt=" +
            //水印内容
            encodeURIComponent("") +
            "&token=" +
            getToken();
          this.previewModal.visible = true;
          this.previewModal.loading = false;
          break;
      }
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteConstructionDrawingReview({ uuid: row.uuid })
            .then(async (res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                await that.getColumnsHeader();
                await that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },
    //关闭
    async closePage() {
      this.columns = [];
      this.tableData = [];
      this.getColumnsHeader().finally((_) => {
        this.getTableData();
      });
    },
    search() {
      this.pager.page = 1;
      this.getColumnsHeader();
      this.getTableData();
    },

    reset() {
      this.condition = {
        //提交时间
        createTime: [],
        // 提交人：
        creator: "",
        // 备注：
        remark: "",
        // 名称：
        name: "",
        // 专业：
        major: undefined,
        // 报审时间：
        date: [],
      };
      this.search();
    },

    //查询表头
    getColumnsHeader() {
      let {
        name,
        date,
        createTime,
        creator,
        remark,
        major = "",
      } = this.condition;
      return new Promise((resolve, reject) => {
        getDrawingReviewHeader({
          name,
          startTime: date?.[0] ?? "",
          endTime: date?.[1] ?? "",
          startTimeSub: createTime?.[0] ?? "",
          endTimeSub: createTime?.[1] ?? "",
          creator,
          remark,
          major,
        })
          .then((res) => {
            let source = res?.data ?? [];
            this.columns = [];
            source.forEach((v) => {
              this.columns.push({
                key: v.key,
                title: v.name,
                width: 100,
              });
            });
            resolve();
          })
          .catch((_) => {
            this.columns = [];
            reject();
          });
      });
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let {
        name,
        date,
        createTime,
        creator,
        remark,
        major = "",
      } = this.condition;
      return new Promise((resolve, reject) => {
        pageDrawingReviewBody({
          page,
          pageSize,
          name,
          startTime: date?.[0] ?? "",
          endTime: date?.[1] ?? "",
          startTimeSub: createTime?.[0] ?? "",
          endTimeSub: createTime?.[1] ?? "",
          creator,
          remark,
          major,
        })
          .then((res) => {
            this.tableData = res?.data?.rows || [];
            this.pager.total = res?.data?.totalCount || 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
  },
};
</script>

<style lang="less" scoped>
.screen-conditions-container {
  .more {
    cursor: pointer;
    font-size: 14px;
    color: #1890ff;
    margin-left: 10px;
    padding-top: 6px;
    .anticon {
      font-size: 12px;
    }
  }
}
</style>
